package com.situ.mall.listener;

import com.situ.mall.constant.MqConstant;
import com.situ.mall.constant.OrderStatusConstant;
import com.situ.mall.pojo.Order;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.MultiDelayMessage;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SpringRabbitListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"),
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage message) {
        System.out.println("SpringRabbitListener.listenDelayMessage message: " + message);
        //1.获取信息中订单的orderNo
        Long orderNo = (Long) message.getData();
        //2.查询订单，判断状态：1：未支付  >1 已经支付
        Order order = orderService.selectById(orderNo);
        //订单不存在，或者订单状态>1已经支付
        if (order == null || order.getStatus() > 1) {
            return;
        }
        //3.订单未支付，先判断是否还有剩余的延时时间
        if (message.hasNextDelay()) {
            //有延时时间，需要重新发送延时消息，先获取下一个延时时间
            Long delayValue = message.removeNextDelay();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, message, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelayLong(delayValue);
                    return message;
                }
            });
        } else {
            //4.没有延时时间,说明订单超时未支付
            orderService.updateStatus(orderNo, OrderStatusConstant.ORDER_STATUS_CANCLE);
        }
    }
}
